<?php
require_once 'bootstrap.php'; // Morph autoloader

class Service {
	
    protected $STANDARDACTION = "showPage";
    protected $asParams;
    protected $sPage; // the html page file
    protected $oResponse;
    
    public function __construct($sPage, $bWithSession) {
        $this->asParams = array_merge($_GET, $_POST);
        $this->sPage = $sPage;
        $this->oResponse = new stdClass();
        
        try {
	        if(! $bWithSession) {
		        $this->callMethod();
		        $this->echoResponse();
	        } else {
		        if($this->getSessionStatus() == SESSIONACTIVE) {
		            $this->sUserID = $_SESSION['userID'];
		            $this->sHash = $_SESSION['hash'];
			        $this->callMethod();
			        $this->echoResponse();
		        }
		        else {
		            require_once('index.php');
		        }
	        }	
        } catch(Exception $e) {
        	$this->error($e->getMessage());
		    $this->echoResponse();
        }
    }
    
    /**
     * Calls the method specified by "method" in the GET/POST parameters
     */
    public function callMethod() {
        $sMethod = isset($this->asParams['method']) ? $this->asParams['method'] : $this->STANDARDACTION;
        
        if(in_array($sMethod, get_class_methods($this))) {
            $this->{$sMethod}();
        } else {
            throw new Exception("Method '" . $sMethod . "' not found!");
        }
    }
    
    /**
     * 
     * Adds a JSON-compatible object to the response object by the specified name
     * @param unknown_type $oObject
     * @param unknown_type $sName
     */
    public function addToResponse($oObject, $sName) {
    	$this->oResponse->$sName = $oObject;
    }
    
    /**
     * Adds an "ACTIONSUCCESSFULL" action status to the response object
     */
    public function success() {
        $this->oResponse->sStatus = ACTIONSUCCESSFULL;
    }
    
    /**
     * Adds an "ACTIONUNSUCCESSFULL" action status to the response object
     */
    public function error($sReason) {
        $this->oResponse->sStatus = ACTIONUNSUCCESSFULL;
        $this->oResponse->sReason = $sReason;
    }
    
    /**
     * Encodes the response object to JSON and echos it
     */
    public function echoResponse() {
        $oResponse = json_encode($this->oResponse);
        if($oResponse != "null")
            echo($oResponse);
    }
    
    /**
     * Echos the html page file
     */
    public function showPage() {
		$f = fopen($this->sPage, 'r');
		echo(fread($f, filesize($this->sPage)));
		fclose($f);
    }
    
	/**
	 * Returns the session status
	 */
	public function getSessionStatus() {
        require_once 'util/constants.php';
        
		@session_start();
		if(!isset($_SESSION['userID']) || !isset($_SESSION['hash'])) {
		   	session_destroy();
			return SESSIONINACTIVE;
		}
		return SESSIONACTIVE;
	}
}
?>
